package com.zcc.lesson03;

import com.zcc.lesson02.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TransactionTest {
    public static void main(String[] args) {
        Connection conn=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        try{
            conn=JDBCUtils.getConnection();

            //关闭自动提交的同时，开启事务
            conn.setAutoCommit(false);

            String sql1="update account set money=account.money-? where id=?";
            String sql2="update account set money=account.money+? where id=?";
            String sql3="update account set money=account.money-500 where id=3";

            pstmt=conn.prepareStatement(sql1);
            pstmt.setDouble(1,500);
            pstmt.setDouble(2,1);
            int i1=pstmt.executeUpdate();
            pstmt=conn.prepareStatement(sql3);
            int i2=pstmt.executeUpdate();
            pstmt=conn.prepareStatement(sql2);
            pstmt.setDouble(1,500);
            pstmt.setDouble(2,2);
            int i3=pstmt.executeUpdate();
            //任意一个更新语句影响行数为0时，抛出异常
            //因为影响行数为0说明没有找到目标对象，此时不应该让其他事务成功
            if(i1==0||i2==0||i3==0){
                throw new Exception();
            }
            conn.commit();
            System.out.println("转账成功！");
        }catch (Exception e){
            //显示定义事务失败回滚，不定义也会回滚
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            e.printStackTrace();
        }finally {
            JDBCUtils.release(conn,pstmt,rs);
        }
    }
}
